package cn.easybuy.servlet.pre;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import cn.easybuy.entity.User;
import cn.easybuy.service.UserService;
import cn.easybuy.service.impl.UserServiceImpl;
import cn.easybuy.util.ReturnResult;

public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserService userService = new UserServiceImpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String action = request.getParameter("action");
		if (action != null && action.length()>0) {
			switch (action) {
			case "toRegister":
				//跳转到注册页面
				request.getRequestDispatcher("/pre/register.jsp").forward(request, response);
				break;
			case "doRegister":
				//执行注册用户
				doRegister(request,response);
				break;
			default:
				response.sendRedirect("404.jsp");
				break;
			}
		} else {
			response.sendRedirect("404.jsp");
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	/**
	 * 执行注册用户
	 * @param request
	 * @param response
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void doRegister(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		PrintWriter out = response.getWriter();
		
		User user = new User();
		
		user.setLoginName(request.getParameter("loginName"));
        user.setUserName(request.getParameter("userName"));
        user.setSex(Integer.parseInt(request.getParameter("sex")));
        user.setPassword(request.getParameter("password"));
        user.setIdentityCode(request.getParameter("identityCode"));
        user.setEmail(request.getParameter("email"));
        user.setMobile(request.getParameter("mobile"));
        user.setType(0); // 0 为普通用户，1位管理员
        
        boolean result = userService.register(user);
        
		ReturnResult returnResult = new ReturnResult(0,"注册失败");
		
        if (result) {
        	returnResult.setStatus(1);
        	returnResult.setMessage("注册成功");
		}
		
		String jsonStr = JSON.toJSONString(returnResult);
		
		out.print(jsonStr);
		
		out.flush();
		out.close();
	}

}
